<template>
  <div class="mt-8">
    <h3 class="text-2xl font-bold mb-4 text-yellow-700">表格数据处理器({{ name }})</h3>

    <!-- <div class="mb-4">
      <label class="block mb-2">输入 JSON 数据:</label>
      <el-input type="textarea" v-model="jsonData" :rows="6" placeholder="请输入 JSON 数据"></el-input>
    </div> -->

    <div class="mb-4">
      <label class="block mb-2">输入表头信息 (以逗号分隔):</label>
      <el-input type="textarea" v-model="headers" :rows="3" placeholder="请输入表头信息"></el-input>
    </div>

    <!-- <div class="mb-4">
      <label class="block mb-2">输入搜索项 (以逗号分隔):</label>
      <el-input type="textarea" v-model="searchItems" :rows="3" placeholder="请输入搜索项"></el-input>
    </div> -->

    <div class="mb-4">
      <label class="block mb-2">输入需要过滤的文字 (以空格分隔):</label>
      <el-input v-model="specialStr" :rows="3" placeholder="输入需要过滤的文字"></el-input>
    </div>

    <el-button type="primary" @click="processData">配置表头信息</el-button>

    <!-- <div class="mt-4">
      <label class="block mb-2">处理结果:</label>
      <el-input type="textarea" v-model="result" :rows="10" placeholder="处理结果将显示在这里" readonly></el-input>
    </div> -->

    <div class="mt-4">
      <p class="block mb-2">字段:</p>
      <el-tag v-for="tag in coreStore.fields" type="info" class="cursor-pointer" :key="tag.prop"
        :disable-transitions="false" @click="addTag(tag)">
        {{ tag.originLabel || tag.label }}
      </el-tag>
    </div>

    <div class="bg-[#dfdbd7] p-4 mt-4 drop-shadow-xl">
      <div class="mt-4">
        <p class="block mb-2">参考表头:</p>
        <el-tag v-for="tag in tipHeaders" disabled type="info" class="cursor-pointer" :key="tag"
          :disable-transitions="false" closable>
          {{ tag }}
        </el-tag>
      </div>
      <div class="mt-4">
        <p class="block mb-2">处理后:</p>
        <el-tag v-for="tag in processedCol" :type="curTag == tag ? 'danger' : 'primary'" class="cursor-pointer"
          :key="tag.prop" :disable-transitions="false" closable @close.stop="handleCloseTr(tag)" @click="choose(tag)">
          {{ tag.label }}
        </el-tag>
      </div>

      <div class="mt-4 flex items-center">
        <span class="mr-2">排序</span>
        <el-button-group>
          <el-button type="primary" @click="onSort(1)">首</el-button>
          <el-button type="primary" @click="onSort(2)">前</el-button>
          <el-button type="primary" @click="onSort(3)">后</el-button>
          <el-button type="primary" @click="onSort(4)">尾</el-button>
        </el-button-group>
        <el-button type="danger" class="ml-10" @click="onClear">清空</el-button>
        <div class="ml-4 flex items-center gap-2">
          <span class="text-nowrap">属性</span> <el-input v-model="newItem.propName"></el-input>
          <span class="text-nowrap">字段</span> <el-input v-model="newItem.labelName"></el-input>
          <span class="text-nowrap">类型</span>
          <el-select v-model="newItem.typeName" placeholder="Select">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <span class="text-nowrap">字典</span><el-input v-model="newItem.dicName"></el-input>
          <el-button type="primary" @click="onAdd">添加</el-button>
        </div>
      </div>
    </div>


    <div class="mt-4 flex items-center gap-2">
      <span class="text-nowrap">标签名</span> <el-input v-model="curTag.label"></el-input>
      <span class="text-nowrap">字典</span> <el-input v-model="curTag.dicName"></el-input>
      <span class="text-nowrap">快速搜索</span> <el-switch v-model="curTag.search"></el-switch>
      <span class="text-nowrap">搜索序号</span> <el-input v-model="curTag.searchOrder"></el-input>
      <span class="text-nowrap">搜素标签宽度</span> <el-input v-model="curTag.searchLabelWidth"></el-input>
    </div>

    <!-- <div class="my-4">
      <el-button @click="onCreate">生成代码</el-button>
    </div>

    <div class="mb-4">
      <el-input type="textarea" v-model="aimJson" :rows="4"></el-input>
    </div> -->
  </div>


</template>

<script>
import { addDicName, areSimilar, clone } from '@/comm/tableTooler'
import { useCoreStore } from '@/stores/core';

export default {
  props: ["name"],

  data() {
    return {
      newItem: {
        propName: "",
        labelName: "",
        typeName: "",
        dicName: ""
      },
      coreStore: useCoreStore(),
      jsonData: '',
      headers: '',
      searchItems: '',
      result: '',
      tipOrigin: '',
      tipHeaders: [],
      originCol: [],
      processedCol: [],
      searchItemsArray: [],
      curTag: { label: '' },
      aimJson: '',
      specialStr: '',
      options: [
        {
          value: 'number',
          label: 'number',
        },
        {
          value: 'input',
          label: 'input',
        },
        {
          value: 'select',
          label: 'select',
        },
        {
          value: 'datetime',
          label: 'datetime',
        },
      ]
    };
  },
  mounted() {
    // 读取 localStorage 中的值并赋值
    this.jsonData = localStorage.getItem('jsonData') || '';
    this.headers = localStorage.getItem('headers') || '';
    this.searchItems = localStorage.getItem('searchItems') || '';
    this.specialStr = localStorage.getItem('specialStr') || '';

  },
  computed: {
    searchCol() {
      const ary = this.processedCol.filter(i => i.search);
      ary.sort((a, b) => (Number(b.searchOrder) || 0) - (Number(a.searchOrder) || 0));
      console.log("ary", ary);
      return ary;
    }

  },
  methods: {
    onAdd() {
      if (!this.newItem.propName || !this.newItem.labelName) {
        return;
      }
      const item = { ...coreStore.fields[0] };
      item.prop = this.newItem.propName;
      item.label = this.newItem.labelName;
      item.originLabel = this.newItem.labelName;
      item.type = this.newItem.typeName;
      if (this.newItem.dicName) {
        item.dicName = this.newItem.dicName
      }

      // this.originCol.push(item)
      this.coreStore.addField(item)

      this.newItem.propName = ''
      this.newItem.labelName = ''
      this.newItem.dicName = ''
    },
    setProcessedCol(val) {
      this.processedCol = val;
    },

    onClear() {
      this.processedCol = [];
      console.log("clear")
    },
    handleCloseSearch(tag) {
      tag.search = false
    },
    chooseSearch(tag) {
      this.curTag = tag;
    },
    handleCloseTr(tag) {
      console.log("tag", tag)
      this.processedCol = this.processedCol.filter(i => i != tag)
    },
    addTag(tag) {
      console.log("tag", tag)
      this.processedCol.push(tag)
    },
    choose(tag) {
      this.curTag = tag;
      console.log("cur", this.curTag)
    },
    onSort(direction) {
      const index = this.processedCol.findIndex(col => col === this.curTag);

      if (index === -1) return; // 如果当前标签不在 processedCol 中，直接返回

      let newIndex = index;

      switch (direction) {
        case 1: // 置顶
          newIndex = 0;
          break;
        case 2: // 向前
          if (index > 0) newIndex = index - 1;
          break;
        case 3: // 向后
          if (index < this.processedCol.length - 1) newIndex = index + 1;
          break;
        case 4: // 置底
          newIndex = this.processedCol.length - 1;
          break;
        default:
          return; // 如果方向不在预期范围内，直接返回
      }

      // 进行排序
      const movedItem = this.processedCol.splice(index, 1)[0]; // 移除当前项
      this.processedCol.splice(newIndex, 0, movedItem); // 在新位置插入
    },
    processData() {
      try {

        // 保存输入到 localStorage
        // localStorage.setItem('jsonData', this.jsonData);
        localStorage.setItem('headers', this.headers);
        localStorage.setItem('searchItems', this.searchItems);
        localStorage.setItem('specialStr', this.specialStr);

        // const json = JSON.parse(this.jsonData);
        // this.originCol = [...json.column];

        // const originCol = this.coreStore.fields


        // const headersArray = this.headers.split(',').map(header => header.trim());
        const headersArray = this.headers.split("\\n\\n").map(header => header.trim());
        console.log("headersArray", this.headers, headersArray)

        const searchItemsArray = this.searchItems.split(/[,，]/).map(item => item.trim());

        this.tipHeaders = headersArray
        this.searchItemsArray = searchItemsArray;

        const processedData = this.process([...this.coreStore.fields], headersArray, searchItemsArray);
        // this.result = JSON.stringify(processedData, null, 2);

        this.processedCol = processedData

        // const subColumn = json.group.map(item => {
        //   if (item.column[0].children) {
        //     return {
        //       type: "table",
        //       column: item.column[0].children.column
        //     }
        //   }
        //   return {
        //     type: "form",
        //     column: item.column
        //   }
        // })

        // console.log("subColumn", subColumn)




      } catch (error) {
        // this.result = '处理失败: ' + error.message;
        console.log(error)
      }
    },
    removeParenthesesContent(input) {
      const regex = /[\u4e00-\u9fa5]+/;

      // 使用正则表达式的exec方法查找匹配项
      const match = regex.exec(input);

      // 如果找到匹配项，则返回匹配的中文字符，否则返回空字符串
      return match ? match[0] : '';
    },

    process(column, headers, searchItems) {
      const matchedColumns = [];

      const specialReplacements = this.specialStr ? this.specialStr.split(/\s+/) : []

      column.forEach(col => {
        let temp = ""
        const isMatch = headers.some(header => {
          //只保留中文部分
          const colLabel = this.removeParenthesesContent(col.label)
          if (colLabel === header || areSimilar(colLabel, header, specialReplacements)) {
            temp = header
            return true
          }

          return false;
        });

        col.originLabel = col.label
        if (isMatch) {
          col.label = temp
          matchedColumns.push(col);
        }
      });

      const result = {
        // id: jsonData.id,
        column: matchedColumns,
        // name: jsonData.name
      };

      matchedColumns.sort((a, b) => {
        return headers.indexOf(a.label) - headers.indexOf(b.label);
      });

      matchedColumns.forEach(col => {
        const header = headers.find(header => col.label === header || areSimilar(col.label, header, specialReplacements));
        if (header) {
          col.label = header;
        }
      });

      let searchOrder = 300;
      matchedColumns.forEach(col => {
        if (searchItems.includes(col.label)) {
          col.search = true;
          col.searchOrder = searchOrder;
          searchOrder -= 30;
        }
      });

      return matchedColumns;
    },
    onCreate() {
      const json = JSON.parse(this.jsonData);
      json.column = clone(this.processedCol)
      addDicName(json.column)
      this.aimJson = JSON.stringify(json, null, 2)
    }
  }
};
</script>

<style scoped>
/* 可以在这里添加自定义样式 */
</style>
